// 表单编辑页面月表单配置列表页  预览弹窗
import React from "react";
import { SchemaForm, FormButtonGroup, Submit, createFormActions } from "@formily/antd";
import {
  Input,
  Radio,
  Checkbox,
  Select,
  DatePicker,
  NumberPicker,
  Rating,
  ArrayTable,
} from "@formily/antd-components";
import { Modal, Spin, Button, Popconfirm, Icon, Row } from "antd";
import {
  CustomTreeSelectFieldSingle,
  // CustomTreeSelectFieldMultiple,
} from "components/formily/components/CustomTreeSelectFieldFormily";
import CustomUploadFieldFormily from "components/formily/components/CustomUploadFieldFormily";
// import ArrayTable from 'components/formily/form-editor/widgetConfig/components/ArrayTable';
import { getFileUrl } from "services/public.js";
import IframeWrapper from 'components/IframeWrapper';
import { transformEditorToFormily } from 'utils/comm';
import styles from "./CustomForm.less";
import "antd/dist/antd.css";

export function getUploadValue(value) {
  function formatFileList(arr) {
    return arr
      .map((item, idx) => {
        const fileName = (Object.keys(item) || [])[0];
        if (fileName) {
          return {
            name: fileName,
            percent: 100,
            response: {
              datas: item[fileName],
            },
            status: "done",
            uid: -idx,
            url: getFileUrl(item[fileName]),
          };
        } else {
          return null;
        }
      })
      .filter(Boolean);
  }
  if (Array.isArray(value)) {
    return formatFileList(value);
  }
  const result = JSON.parse(value);
  if (Array.isArray(result)) {
    return formatFileList(result);
  }
  return [];
}
const actionsPC = createFormActions();
// window.act = actionsPC;

class CustomForm extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      currentMode: 'PC', // PC / MOBILE
    };
  }

  componentDidMount() {
    const { noticeBusinessSystem } = this.props;
    if (noticeBusinessSystem) {
      this.notify({
        type: 'formReady',
      });
      window.addEventListener('message', this.onMessage);
    }
  }

  componentWillUnmount() {
    const { noticeBusinessSystem } = this.props;
    if (noticeBusinessSystem) {
      window.removeEventListener('message', this.onMessage);
    }
  }

  notify = (message) => {
    if (window.parent !== window) { // 确保在iframe中
      window.parent.postMessage(message, '*');
    }
  }

  onMessage = e => {
    if (e.data && e.data.type === 'setFormData') {
      const { data } = e.data;
      if (data) {
        Object.keys(data).forEach((key) => {
          actionsPC.setFieldState(key, state => {
            state.value = data[key];
          })
        });
      }
    }
  }


  handleOk = values => {
    // const { formValue } = this.state;
    const { onOk } = this.props;
    if (values && onOk) {
      onOk(values);
    }
  };

  handleCancel = () => {
    const { onCancel } = this.props;
    if (onCancel) onCancel();
  };

  renderSelectButtons() {
    const { showMobile } = this.props;
    const { currentMode } = this.state;
    if (!showMobile){
      return null;
    }
    let pcButtonType = 'normal';
    let mobileButtonType = 'normal';
    if (currentMode === 'PC') {
      pcButtonType = 'primary';
    } else if (currentMode === 'MOBILE') {
      mobileButtonType = 'primary';
    }
    return (
      <Row className={styles.header}>
        <Button type={pcButtonType} onClick={() => this.setState({ currentMode: 'PC' })}>
          <Icon type="laptop" />
          电脑
        </Button>
        <Button type={mobileButtonType} onClick={() => this.setState({ currentMode: 'MOBILE' })}>
          <Icon type="mobile" />
          手机
        </Button>
      </Row>
    );
  }

  renderFormPC() {
    const {
      confirmLoading,
      formConfigData = {},
      dataLoading = false,
      isView = false,
      emptyWord = "",
      action = "",
      showMobile,
      editable = true,
      initialValues,
      showSaveDraft = false,
      formUrl = "",
      isExternalForm,
    } = this.props;
    const newFormConfigData = transformEditorToFormily(formConfigData);
    return (
      <Spin spinning={dataLoading}>
        {isExternalForm === true ? (
          <SchemaForm>
            <IframeWrapper
              autoFitHeight
              src={formUrl}
              style={{ height: 352 }}
              iframeStyle={{ height: 352 }}
              getFrameRef={ref => { this.iframeRef = ref; }}
            />
            <FormButtonGroup className={styles.formButtonGroup}>
              <Popconfirm
                title={`是否取消${action}？`}
                onConfirm={this.handleCancel}
                okText="是"
                cancelText="否"
                disabled={confirmLoading}
              >
                <Button disabled={confirmLoading}>取消</Button>
              </Popconfirm>
              {showSaveDraft ? (
                <Button
                  disabled={confirmLoading}
                  onClick={() => {
                    const { onSaveDraft } = this.props;
                    actionsPC.getFormState(({ values }) => onSaveDraft(values));
                  }}
                >
                  暂存
                </Button>
              ) : null}
              <Submit
                type="primary"
                showLoading
                loading={confirmLoading}
                onSubmit={values => {
                  this.handleOk(values);
                }}
              >
                {confirmLoading && <Icon type="loading" />}
                {`确认${action}`}
              </Submit>
            </FormButtonGroup>
          </SchemaForm>
          )
         : (
           <SchemaForm
             previewPlaceholder="-"
             editable={editable}
             actions={actionsPC}
             className={[styles.schemaForm,showMobile ? styles.hasMobile : ''].join(' ')}
             components={{
            Input,
            TextArea: Input.TextArea,
            Select,
            NumberPicker,
            CheckboxGroup: Checkbox.Group,
            RadioGroup: Radio.Group,
            DatePicker,
            RangePicker: DatePicker.RangePicker,
            Rating,
            SelectPersonField: CustomTreeSelectFieldSingle,
            Attachment: CustomUploadFieldFormily,
            ArrayTable,
          }}
             schema={newFormConfigData}
             initialValues={initialValues}
             autoComplete="off"
           >
             {JSON.stringify(formConfigData) === "{}" && emptyWord && (
             <div className={styles.no_data}>
               <span>{emptyWord || "暂无表单数据"}</span>
             </div>
              )}
             {!isView && (
             <FormButtonGroup className={styles.formButtonGroup}>
               <Popconfirm
                 title={`是否取消${action}？`}
                 onConfirm={this.handleCancel}
                 okText="是"
                 cancelText="否"
                 disabled={confirmLoading}
               >
                 <Button disabled={confirmLoading}>取消</Button>
               </Popconfirm>
               { showSaveDraft ? (
                 <Button
                   disabled={confirmLoading}
                   onClick={() => {
                    const { onSaveDraft } = this.props;
                    actionsPC.getFormState(({ values }) => onSaveDraft(values));
                  }}
                 >
                   暂存
                 </Button>
              ) : null }
               <Submit
                 type="primary"
                 showLoading
                 loading={confirmLoading}
                 onSubmit={values => {
                  this.handleOk(values);
                }}
               >
                 {confirmLoading && <Icon type="loading" />}

                 {`确认${action}`}
               </Submit>
             </FormButtonGroup>
            )}
           </SchemaForm>
)}
        
      </Spin>
    );
  }

  renderFormMobile() {
    const {
      formConfigData = {},
      dataLoading = false,
      // isView = false,
    } = this.props;
    /*
    if (!isView) {
      throw new Error("目前只支持预览")
    }
    */

    return (
      <Spin spinning={dataLoading}>
        <IframeWrapper
          style={{
            margin: '10px auto',
            width: 377,
            height: 668,
          }}
          autoFitHeight
          src="/flow-phone/form?noTheme=1"
          maxHeight={800}
          messageHandlers={[
            (msg) => {
              if (msg.type === 'ready'){
                if (this.iframeRef && this.iframeRef.current) {
                  this.iframeRef.current.contentWindow.postMessage({
                    type: 'formConfig',
                    setting: {
                      formConfig: formConfigData,
                    },
                  });
                }
              }
            },
          ]}
          getFrameRef={ref => { this.iframeRef = ref; }}
        />
      </Spin>
    );
  }

  renderForm() {
    const { currentMode } = this.state;
    if (currentMode === 'PC') {
      return this.renderFormPC();
    }
    if (currentMode === 'MOBILE') {
      return this.renderFormMobile();
    }
  }

  render() {
    const {
      visible,
      confirmLoading,
      title = "",
      isView = false,
      withModal = true,
      showMobile,
    } = this.props;


    // let modalProps = {
    //   // onOk: this.handleOk,
    //   // onCancel: this.handleCancel,
    //   footer: [
    //     <Popconfirm
    //       title={`是否取消${action}？`}
    //       onConfirm={this.handleCancel}
    //       okText="是"
    //       cancelText="否"
    //     >
    //       <Button>取消</Button>
    //     </Popconfirm>,
    //     <Button type="primary" onClick={this.handleOk} loading={confirmLoading}>
    //       确认申请
    //     </Button>,
    //   ],
    //   onCancel: this.handleCancel,
    // };

    let modalProps = {
      footer: null,
      onCancel: this.handleCancel,
    };
    if (isView) {
      modalProps = {
        footer: <Button onClick={this.handleCancel}>返回</Button>,
        onCancel: this.handleCancel,
      };
    }
    if (!withModal) {
      return (
        <div
          className={[styles.wrap, styles.bgfff, 'dynamic-theme'].join(' ')}
          style={{ padding: 12 }}
        >
          {this.renderForm()}
        </div>
      );
    }
    return (
      <Modal
        title={title || "表单预览"}
        visible={visible}
        {...modalProps}
        width="1000px"
        centered
        maskClosable={false}
        confirmLoading={confirmLoading}
        wrapClassName={[styles.wrap, showMobile ? styles.mobile : ''].join(' ')}
      >
        {this.renderSelectButtons()}
        {this.renderForm()}
      </Modal>
    );
  }
}

export default CustomForm;
